package com.fjwt.gz.service.activity.coupon.notify;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.coupon.lkls.LklspayCouponWriteNotifyService;
import com.fjwt.gz.db.entity.AwardCouponNotifyEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.PayOrderEntity;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import com.fjwt.gz.service.impl.AwardCouponNotifyService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.PayOrderService;
import com.fjwt.gz.service.impl.ScoreRecordTotalService;
import com.fjwt.gz.service.activity.BaseActivityService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LklspayCouponWriteService implements ChannelCouponWriteService {

    private static final Logger lklsPayLogger = LoggerFactory.getLogger("lklsPay");

    @Autowired
    private AwardCouponNotifyService awardCouponNotifyService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ScoreRecordTotalService scoreRecordService;
    @Autowired
    private LklspayCouponWriteNotifyService lklspayCouponWriteNotifyService;

    private static String logPrefix = "拉卡拉卡券核销回调:";

    @Override
    public String addNotifyRecord(Map<String, Object> requestMap) {

        lklsPayLogger.info(logPrefix + "添加回调信息记录进来的参数是：{}", JSONUtil.toJsonStr(requestMap));
        Date date = new Date();
        AwardCouponNotifyEntity couponNotifyEntity = new AwardCouponNotifyEntity();

        String couponThirdId = requestMap.get("thirdCouponId").toString();
        lklsPayLogger.info(logPrefix + "三方卡券ID:{}", couponThirdId);

        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponThirdId);
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);
        if (ObjectUtil.isEmpty(fansAwardEntity)) {
            lklsPayLogger.info("卡券ID：{}，此卡券不是营销平台创建，直接返回，不记录数据库", couponThirdId);
            return "false";
        }

        if ("USED".equals(requestMap.get("tradeStatus"))) {
            couponNotifyEntity.setNotifyState(0);//已核销
        } else {
            couponNotifyEntity.setNotifyState(2);//已过期
        }
        couponNotifyEntity.setCouponThirdId(couponThirdId);
        couponNotifyEntity.setIfcode("lklspay");
        couponNotifyEntity.setState(1);//回调进来的都是状态1未同步
        couponNotifyEntity.setNotifyJson(JSONUtil.toJsonStr(requestMap));
        couponNotifyEntity.setCreatedAt(date);
        couponNotifyEntity.setUpdatedAt(date);
        couponNotifyEntity.setSourceType(1);
        lklsPayLogger.info(logPrefix + "添加回调信息记录:{}", JSONUtil.toJsonStr(couponNotifyEntity));
        boolean save = awardCouponNotifyService.save(couponNotifyEntity);
        if (save) {
            return "true";
        } else {
            return "false";
        }
    }

    @Override
    public Map<String, Object> paraseParamters(HttpServletRequest request) throws IOException {
        lklsPayLogger.info(logPrefix + "request:{}", JSONUtil.toJsonStr(request));
        Map map = new HashMap<String, String>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Object key : parameterMap.keySet()) {
            map.put(key.toString(), ((String[]) parameterMap.get(key))[0]);
        }
        lklsPayLogger.info(logPrefix + "解析参数返回的信息是：{}", JSONUtil.toJsonStr(map));
        return map;
    }

    @Override
    public void couponDoNotice(AwardCouponNotifyEntity couponNotifyEntity) throws Exception {
        lklsPayLogger.info(logPrefix + "处理逻辑进来的参数是：{}", JSONUtil.toJsonStr(couponNotifyEntity));
        //通过卡券三方id是否存在，如不存在，更新回调记录表，添加备注
        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponNotifyEntity.getCouponThirdId());
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);

        if (ObjectUtil.isNotEmpty(fansAwardEntity)) {
            if (fansAwardEntity.getState() == 1) {
                //卡券状态已更改
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("此订单已经推送过");
                lklsPayLogger.info(logPrefix + "处理逻辑,此卡券此订单已经推送过,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            } else {
                // 处理卡券核销是否进行奖励积分
                scoreRecordService.couponWriteSendScore(fansAwardEntity);
                //是卡券营销平台创建,卡券核销后的处理
                lklsPayLogger.info(logPrefix + "extraJson:{}", fansAwardEntity.getExtraJson());
                JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                if (extraJson != null && fansAwardEntity.getExtraJson().contains("templateNo")) {
                    String templateNo = extraJson.getString("templateNo");
                    BaseActivityService activityService = SpringBeansUtil.getBean(templateNo + "Service", BaseActivityService.class);
                    // 支付通道接口实现不存在
                    if (activityService == null) {
                        lklsPayLogger.info(templateNo + "Service,接口不存在");
                        throw new BizException(templateNo + "Service,接口不存在");
                    }
                    JSONObject json = JSONObject.parseObject(JSONUtil.toJsonStr(fansAwardEntity));
                    activityService.run(json);
                }
                FansAwardEntity fansAwardEntityUpdate = new FansAwardEntity();
                fansAwardEntityUpdate.setFansAwardId(fansAwardEntity.getFansAwardId());
                fansAwardEntityUpdate.setState(1);
                fansAwardEntityUpdate.setWriteTime(new Date());
                //如果能通过三方卡券id查询到订单，则添加商户号，（此订单核销属于新平台的订单，如果没有则表示是老平台的订单，就没有商户号）
                LambdaQueryWrapper<PayOrderEntity> payOrderGw = PayOrderEntity.gw();
                payOrderGw.eq(PayOrderEntity::getCouponThirdId, fansAwardEntity.getCouponThirdId());
                PayOrderEntity payOrderEntity = payOrderService.getBaseMapper().selectOne(payOrderGw);
                if (ObjectUtil.isNotEmpty(payOrderEntity)) {
                    fansAwardEntityUpdate.setMchNo(payOrderEntity.getMchNo());
                }
                lklsPayLogger.info(logPrefix + "此卡券核销更新数据，更新数据的信息是：{}", JSONUtil.toJsonStr(fansAwardEntityUpdate));
                fansAwardService.updateById(fansAwardEntityUpdate);

                //更新回调数据状态
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("核销成功");
                lklsPayLogger.info(logPrefix + "核销成功,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            }
        } else {
            //卡券不是营销平台创建
            AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
            couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
            couponNotifyUpdate.setState(2);
            couponNotifyUpdate.setRemark("此卡券不是营销平台创建");
            lklsPayLogger.info(logPrefix + "处理逻辑,此卡券不是营销平台创建,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
            awardCouponNotifyService.updateById(couponNotifyUpdate);
        }
    }
}
